//
//  TNRateTableViewController.m
//  TravelNotes
//
//  Created by 黄锋 on 15/8/13.
//  Copyright (c) 2015年 王浩宇. All rights reserved.
//

#import "TNRateTableViewController.h"
#import <AFNetworking.h>
#import "TNRateTableViewCell.h"

#define kURL @"http://chanyouji.com/api/currency_exchanges.json"

@interface TNRateTableViewController () <UITextFieldDelegate, UIAlertViewDelegate>

{
    float _rate[4];
}
@property(nonatomic, strong) NSMutableArray *dataArray;
@property(nonatomic, strong) NSArray *countryArray;
@property(nonatomic, strong) NSArray *moneyArray;

@end

@implementation TNRateTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (_model.currency_display && _model.currency_code) {
        _countryArray = @[_model.currency_code, @"CNY", @"USD", @"EUR"];
        _moneyArray = @[_model.currency_display, @"人民币", @"美元", @"欧元"];
    } else {
        _countryArray = @[@"CNY", @"USD", @"EUR"];
        _moneyArray = @[@"人民币", @"美元", @"欧元"];
    }
    self.navigationItem.title = @"实时汇率";
    [self.tableView registerClass:[TNRateTableViewCell class] forCellReuseIdentifier:@"TNRateTableViewCell"];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tapGestureRecognizer];
    [self parserData];
}

- (void)tapAction
{
    NSArray *array = [self.tableView visibleCells];
    for (int i = 10000; i < 10000 + _countryArray.count; i++) {
        TNRateTableViewCell *cell = (TNRateTableViewCell *)array[i - 10000];
        UITextField *tf = cell.textField;
        if ([tf.text isEqualToString:@""]) {
            tf.text = @"0.00";
            cell.name.textColor = [UIColor blackColor];
            cell.textField.textColor = [UIColor blackColor];
        }
    }
    [self.view endEditing:YES];
}

- (void)parserData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:kURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        _dataArray = [array mutableCopy];
        [self.tableView reloadData];
        [self getRate];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:nil message:@"网络出错" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"重试", nil];
        [view show];
    }];
}

- (void)getRate
{
    _rate[0] = 1.0;
    int j = 0;
    for (NSDictionary *dic in _dataArray) {
        NSString *from = dic[@"currency_from"];
        NSString *to = dic[@"currency_to"];
        if ([to isEqualToString:_model.currency_code]) {
            for (int i = 1; i < 4; i++) {
                NSString *str = _countryArray[i];
                if ([from isEqualToString:str]) {
                    NSString *rate = dic[@"exchange_rate"];
                    _rate[i] = [rate floatValue];
                    if (++j == 3) {
                        return;
                    }
                }
            }
        }
    }
    for (int i = 1; i < 4; i++) {
        if (_rate[i] == 0) {
            _rate[i] = 1.0;
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _countryArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     TNRateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TNRateTableViewCell" forIndexPath:indexPath];
     NSInteger index = indexPath.row;
 // Configure the cell...
     NSString *string = _countryArray[index];
     [cell.pic setImage:[UIImage imageNamed:string]];
     cell.name.text = string;
     cell.money.text = _moneyArray[index];
     cell.textField.tag = 10000 + index;
     cell.textField.delegate = self;
     return cell;
 }

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSMutableString *newString = [textField.text mutableCopy];
    if (range.length) {
        [newString deleteCharactersInRange:range];
    } else {
        [newString insertString:string atIndex:range.location];
    }
    CGFloat count = [newString floatValue];
    NSArray *array = [self.tableView visibleCells];
    NSInteger index = textField.tag - 10000;
    for (int i = 0; i < _countryArray.count; i++) {
        TNRateTableViewCell *cell = (TNRateTableViewCell *)array[i];
        UITextField *tf = cell.textField;
        if (index != i) {
            CGFloat ff = count * _rate[index] / _rate[i];
            tf.text = [NSString stringWithFormat:@"%.2f", ff];
        }
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    textField.text = @"";
    NSArray *array = [self.tableView visibleCells];
    for (int i = 10000; i < 10000 + _countryArray.count; i++) {
        TNRateTableViewCell *cell = (TNRateTableViewCell *)array[i - 10000];
        if (i != textField.tag) {
            UITextField *tf = (UITextField *)[cell viewWithTag:i];
            tf.text = @"0.00";
            cell.name.textColor = [UIColor blackColor];
            cell.textField.textColor = [UIColor blackColor];
        } else {
            cell.name.textColor = [UIColor blueColor];
            cell.textField.textColor = [UIColor blueColor];
        }
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self parserData];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
